package com.my.study.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author: yidujun
 * @create: 2022/04/07 21:09
 */
@Slf4j
@RestController
@RequestMapping("/open/api")
public class OpenApiController {

    private static String APP_KEY = "RuV407cd";
    private static String APP_SECRET = "5aa081b67fab5b23d6f8f91df41c2423cc23f02a";

    @GetMapping("/test")
    public Object test() {
        return "这是一个中午！";
    }

    @GetMapping("/getAccessToken")
    public Object getAccessToken(@RequestParam(value = "appKey") String appKey) {
        String url = "https://mtest.51ifind.com/enterprise-code-api/open/api/getAccessToken";
        Map<String, Object> params = new HashMap<>(6);
        params.put("qym_appKey", appKey);
        params.put("qym_timestamp", System.currentTimeMillis());
        params.put("qym_sign", SignUtils.createSign(params, APP_SECRET));

        HttpResponse execute = HttpUtil.createPost(url)
                .form(params)
                .execute();
        return execute.body();
    }

    @GetMapping("/match")
    public Object match(@RequestParam(value = "appKey") String appKey,
                        @RequestParam(value = "accessToken") String accessToken,
                        @RequestParam(value = "socialCreditCode") String socialCreditCode) {
        String url = "https://mtest.51ifind.com/enterprise-code-api/open/api/policy/match/list";
        Map<String, Object> params = new HashMap<>(10);
        params.put("qym_appKey", appKey);
        params.put("qym_timestamp", System.currentTimeMillis());
        params.put("qym_accessToken", accessToken);
        params.put("socialCreditCode", socialCreditCode	);
        params.put("qym_sign", SignUtils.createSign(params, APP_SECRET));
        HttpResponse execute = HttpUtil.createPost(url)
                .form(params)
                .execute();
        return execute.body();
    }

    private static class SignUtils {
        /**
         * 构建签名
         *
         * @param params    参数
         * @param appSecret 密钥
         * @return 签名
         */
        public static String createSign(Map<String, Object> params, String appSecret) {
            if (CollUtil.isEmpty(params)) {
                return "";
            }
            Set<String> keySet = params.keySet();
            List<String> paramsNames = new ArrayList<>(keySet);
            // 升序
            Collections.sort(paramsNames);
            // 拼接
            StringBuilder sb = new StringBuilder();
            for (String paramsName : paramsNames) {
                Object value = params.get(paramsName);
                if (null != value && StrUtil.isNotBlank(value.toString())) {
                    sb.append(paramsName).append(value);
                }
            }
            String source = appSecret + sb.toString() + appSecret;
            String sign = "";
            try {
                sign = DigestUtil.md5Hex(source.getBytes(StandardCharsets.UTF_8)).toUpperCase();
            } catch (Exception e) {
                log.error("构建签名错误，params={}", params, e);
            }
            return sign;
        }
    }
}
